package com.shen.accountbook.bean.temp.biz;

import android.database.Cursor;

import com.shen.accountbook.bean.ReportFormsBean;
import com.shen.accountbook.bean.temp.NoteBeanTemp;
import com.shen.accountbook.greendao.DaoSession;
import com.shen.accountbook.greendao.NoteBeanTempDao;
import com.shen.accountbook.greendao.SecondSortBeanDao;
import com.shen.accountbook.greendao.manager.DaoManager;
import com.shen.accountbook.utils.L;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * author:  shen
 * date:    2018/9/15
 */
public class NoteBeanTempBiz {
    DaoManager mDaoManager;
    DaoSession mDaoSession;
    NoteBeanTempDao mDao;

    public NoteBeanTempBiz(){
        mDaoManager = DaoManager.getInstance();
        mDaoSession = mDaoManager.getSession();
        mDao = mDaoSession.getNoteBeanTempDao();
    }

    /**
     * 插入数据
     * @param bean
     */
    public boolean insertAuto(NoteBeanTemp bean){

        long rowId = mDao.insert(bean);;

        if(rowId > 0){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 插入数据
     * @param bean
     */
    public void update(NoteBeanTemp bean){
        mDao.update(bean);
    }

    /**
     * 获取全部的
     * @return
     */
    public List<NoteBeanTemp> getNoteBean(){
        List<NoteBeanTemp> beanList = mDao.queryBuilder().list();
        return beanList;
    }

    /**
     * 20个 为一页
     * @param offset
     * @return
     */
    public List<NoteBeanTemp> getNoteBean(int offset){
        List<NoteBeanTemp> beanList = mDao.queryBuilder().offset(offset * 20).limit(20).list();
        return beanList;
    }

    /**
     * 根据第一分类获取
     * @param firstId
     * @return
     */
    public List<NoteBeanTemp> getBeanByFirstId(long firstId){
        List<NoteBeanTemp> beanList = mDao.queryBuilder()
                .where(NoteBeanTempDao.Properties.First_sort_id.in(firstId)).list();
        return beanList;
    }

    /**
     * 根据第二分类获取
     * @param secondId
     * @return
     */
    public List<NoteBeanTemp> getBeanBySecondId(long secondId){
        List<NoteBeanTemp> beanList = mDao.queryBuilder()
                .where(NoteBeanTempDao.Properties.Second_sort_id.in(secondId)).list();
        return beanList;
    }

    /**
     * 根据时间获取
     * @param date              时间  格式必须是 %Y年%m月
     * @param observer
     */
    public void getBeanByDate(final String date, Observer observer) {

        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Exception { // Observable  (被观察者)
                emitter.onNext(date);
                emitter.onComplete();
            }

        }).observeOn(Schedulers.io())
                .map(new Function<String, List<NoteBeanTemp>>() {
                    @Override
                    public List<NoteBeanTemp> apply(@NonNull String s) throws Exception {

                        List<NoteBeanTemp> meteringSectionList = new ArrayList<>();
                        String sql = "select * " +
                                " from " + NoteBeanTempDao.TABLENAME +
                                " where strftime('%Y年%m月'," + NoteBeanTempDao.Properties.CreateDate.columnName + ") = '" + s + "'" +
                                "order by " + NoteBeanTempDao.Properties.CreateDate.columnName;

                        Cursor cursor = mDaoSession.getDatabase().rawQuery(sql, null);

                        try {
                            if (cursor != null && cursor.getCount() != 0) {
                                if (cursor.moveToFirst()) {
                                    do {
                                        setBean(meteringSectionList, cursor);
                                    } while (cursor.moveToNext());
                                }
                            }else {
                                L.i("(cursor == null || cursor.getCount() == 0)");
                            }
                        }catch (Exception e){
                            L.i("getBeanByDate -- beanTemp.toString()" + e);
                        } finally {
                            if(cursor != null) {
                                cursor.close();
                            }
                        }
                        return meteringSectionList;
                    }

                    private void setBean(List<NoteBeanTemp> meteringSectionList, Cursor cursor) {
                        NoteBeanTemp beanTemp = new NoteBeanTemp();
                        beanTemp.__setDaoSession(new NoteBeanTempBiz().mDaoSession);
                        beanTemp.setId(cursor.getLong(NoteBeanTempDao.Properties.Id.ordinal));
                        beanTemp.setFirst_sort_id(cursor.getLong(NoteBeanTempDao.Properties.First_sort_id.ordinal));
                        beanTemp.setSecond_sort_id(cursor.getLong(NoteBeanTempDao.Properties.Second_sort_id.ordinal));
                        beanTemp.setThird_sort_id(cursor.getLong(NoteBeanTempDao.Properties.Third_sort_id.ordinal));
                        beanTemp.setMoney(cursor.getFloat(NoteBeanTempDao.Properties.Money.ordinal));
                        beanTemp.setRemarks(cursor.getString(NoteBeanTempDao.Properties.Remarks.ordinal));
                        beanTemp.setImg(cursor.getString(NoteBeanTempDao.Properties.Img.ordinal));
                        beanTemp.setCreateDate(cursor.getString(NoteBeanTempDao.Properties.CreateDate.ordinal));

                        meteringSectionList.add(beanTemp);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }


    /**
     * 根据时间获取 -- 报表 按照分类
     * @param date              时间  格式必须是 %Y年%m月
     * @param observer
     */
    public void getBeanByDateReport(final String date, Observer observer) {

        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Exception { // Observable  (被观察者)
                emitter.onNext(date);
                emitter.onComplete();
            }

        }).observeOn(Schedulers.io())
                .map(new Function<String, ReportFormsBean>() {
                    @Override
                    public ReportFormsBean apply(@NonNull String s) throws Exception {

                        List<NoteBeanTemp> meteringSectionList = new ArrayList<>();
                        String sql = "select sum("+ NoteBeanTempDao.Properties.Money.columnName +"), " +
                                NoteBeanTempDao.Properties.Second_sort_id.columnName + "," +
                                " (select " + SecondSortBeanDao.Properties.Second_sort_name.columnName +
                                " from " + SecondSortBeanDao.TABLENAME +
                                " where " + SecondSortBeanDao.TABLENAME + "." + SecondSortBeanDao.Properties.Second_sort_id.columnName + "=" +
                                NoteBeanTempDao.TABLENAME + "." + NoteBeanTempDao.Properties.Second_sort_id.columnName + ")" +
                                " from " + NoteBeanTempDao.TABLENAME +
                                " where strftime('%Y年%m月'," + NoteBeanTempDao.Properties.CreateDate.columnName + ") = '" + s + "'" +
                                "group by " + NoteBeanTempDao.Properties.Second_sort_id.columnName;




                        Cursor cursor = mDaoSession.getDatabase().rawQuery(sql, null);

                        ReportFormsBean reportFormsBean = new ReportFormsBean();
                        float money = 0;
                        try {
                            if (cursor != null && cursor.getCount() != 0) {
                                if (cursor.moveToFirst()) {
                                    do {
                                        L.i("cursor.getFloat(0) :" + cursor.getFloat(0) +
                                                "cursor.getLong(1) :" + cursor.getLong(1) +
                                                "cursor.getString(2) :" + cursor.getString(2));

                                        setBean(reportFormsBean, money, cursor);
                                    } while (cursor.moveToNext());
                                }
                            }else {
                                L.i("(cursor == null || cursor.getCount() == 0)");
                            }
                        }catch (Exception e){
                            L.i("getBeanByDate -- beanTemp.toString()" + e);
                        } finally {
                            if(cursor != null) {
                                cursor.close();
                            }
                        }
                        return reportFormsBean;
                    }

                    private void setBean(ReportFormsBean reportFormsBean, float money, Cursor cursor) {
                        ReportFormsBean.TMoneyBean tMoneyBean = new ReportFormsBean.TMoneyBean();
                        tMoneyBean.setMoney(cursor.getFloat(0));
                        tMoneyBean.setTypeId(cursor.getLong(1));
                        tMoneyBean.setTypeName(cursor.getString(2));
                        tMoneyBean.setBackColor("#ffb073");
                        money += cursor.getFloat(0);

                        reportFormsBean.setTotal(money);
                        reportFormsBean.setDate(date);

                        List<ReportFormsBean.TMoneyBean> tMoneyBeanList = reportFormsBean.getTypeMoney();

                        if(tMoneyBeanList != null){
                            tMoneyBeanList.add(tMoneyBean);
                            reportFormsBean.setTypeMoney(tMoneyBeanList);
                        }else {
                            tMoneyBeanList = new ArrayList<>();
                            tMoneyBeanList.add(tMoneyBean);
                            reportFormsBean.setTypeMoney(tMoneyBeanList);
                        }

                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }
}
